import { cityList } from "./cityData"

export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join("/") + " " + [hour, minute, second].map(formatNumber).join(":")
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : "0" + s
}

/**
 *
 * @param num: number 要转换的大额数值
 * @param float: number 要保留的浮点数个数，默认为3
 * @returns : string 处理后的结果 带"亿"或"万"单位
 * @description 把一串大额的数值转换成"x.xxx亿/万"的字符串
 */
export const localNum = (num: number, float: number = 3) => {
  const size = num.toString().split("")
  let res: string = ""
  let ending: string = ""

  let i: number = 0
  if (size.length >= 9) {
    for (i; i < size.length - 8; i++) {
      res += size[i].toString()
    }
    ending = "亿"
    res += float > 0 ? "." : ""
  } else if (size.length >= 5) {
    for (i; i < size.length - 4; i++) {
      res += size[i].toString()
    }
    ending = "万"
    res += float > 0 ? "." : ""
  }

  const limit = i ? float + i : size.length
  for (i; i < limit; i++) {
    res += size[i]
  }

  return (res += ending)
}

/**
 *
 * @param time: number 出生日期时间戳
 * @returns res { astro: "xx星座", offsetAge: "xx后" }
 * @description 传入一个出生日期时间戳，返回星座和年代"xx后"
 */
export const getAstroAndOffsetAge = (time: number) => {
  const res = {
    astro: "",
    offsetAge: "",
  }
  const birthday = new Date(time)

  const year = birthday.getFullYear()
  const month = birthday.getMonth() + 1
  const date = birthday.getDate()

  const offset = year % 10
  res.offsetAge = (year - (year % (offset >= 5 ? 5 : 10))).toString().split("").slice(2, 4).join("") + "后"

  let s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯"
  let arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]
  res.astro = s.substr(month * 2 - (date < arr[month - 1] ? 2 : 0), 2) + "座"

  return res
}

/**
 *
 * @param province: number | string 省份代码
 * @param city: number | string 城市代码
 * @returns res { provinceName: "省份名", cityName: "城市名" }
 * @description 传入省份代码和城市代码，返回省份和城市名
 */
export const getProvinceAndCity = (province: number | string, city: number | string) => {
  const provinceData = cityList.filter(item => item.provinceCode === province.toString())[0]
  const cityData = provinceData.mallCityList.filter(item => item.cityCode === city.toString())[0]

  return {
    provinceName: provinceData.provinceName,
    cityName: cityData.cityName,
  }
}

type FunctionLike = (...params: any[]) => any

/**
 *
 * @param callback : 要防抖执行的函数
 * @param delay: number 防抖时间
 * @param useResult: boolean 默认为false不获取返回值，true时可以使用await或.then获取回调函数的返回值
 * @returns db_callback : 经过防抖处理后的函数
 * @description 防抖处理后的函数连续调用时会重新计时，永远在最后一次触发的delay时间之后执行
 */
export const deBounce = <T extends FunctionLike>(
  callback: T,
  delay: number,
  useResult: boolean = false,
  _this?: any
) => {
  let timer: number
  return (...params: Parameters<T>) => {
    if (useResult) {
      return new Promise<ReturnType<T>>(resolve => {
        clearTimeout(timer)
        timer = setTimeout(() => {
          resolve(callback.bind(_this)(...params))
        }, delay)
      })
    } else {
      clearTimeout(timer)
      timer = setTimeout(() => {
        callback.bind(_this)(...params)
      }, delay)
      return
    }
  }
}

//删除数组中的首个目标元素，成功返回删除项，失败返回undefined
export const removeArrItem = (arr: any[], target: any) => {
  const targetIndex = arr.indexOf(target)
  if (targetIndex === -1) return
  return arr.splice(targetIndex, 1)[0]
}

//把歌手数组和专辑名传入格式化， 返回 "aaa/bbb - albumName"
export const formatSingerAndAlbum = (ar: any[], alName?: string) => {
  let res = ""
  ar.forEach((ar, index) => (res += index ? "/" + ar.name : ar.name))
  if (alName) res += " - " + alName
  return res
}

/**
 * 
 * @param min: number 最小值
 * @param max: numebr 最大值(包含)
 * @returns number 
 * @description 传入最小值与最大值，返回包含两端的一个随机整数
 */
export const randomInt = (min: number, max: number) => Math.round(Math.random() * (max - min) + min)
